package fs

import (
	"github.com/sirupsen/logrus"
	"mydocker/cgroups/resource"
	"mydocker/common"
	"os"
	"path"
	"strconv"
)

type CpuSetSubsystem struct {
}

func (*CpuSetSubsystem) Name() string {
	return "cpuset"
}

func (c *CpuSetSubsystem) Set(cgroupPath string, res *resource.ResourceConfig) error {
	if res.CpuSet == "" {
		return nil
	}
	subsystemCgroupPath, err := getCgroupPath(c.Name(), cgroupPath, true)
	if err != nil {
		logrus.Errorf("get %s path, err: %v", cgroupPath, err)
		return err
	}
	logrus.Infof("cpuset subsystemCgroupPath: %s", subsystemCgroupPath)
	if err = os.WriteFile(path.Join(subsystemCgroupPath, "cpuset.cpus"), []byte(res.CpuSet), common.Perm0644); err != nil {
		logrus.Errorf("failed to write file cpuset.cpus, err: %+v", err)
		return err
	}
	logrus.Infof("cpuset.cpus: %s", res.CpuSet)
	return nil
}

func (c *CpuSetSubsystem) Apply(cgroupPath string, pid int) error {
	subsystemCgroupPath, err := getCgroupPath(c.Name(), cgroupPath, true)
	if err != nil {
		logrus.Errorf("get %s path, err: %v", cgroupPath, err)
		return err
	}
	tasksPath := path.Join(subsystemCgroupPath, "tasks")
	if err = os.WriteFile(tasksPath, []byte(strconv.Itoa(pid)), os.ModePerm); err != nil {
		logrus.Errorf("cpuset write pid to tasks, path: %s, pid: %d, err: %v", tasksPath, pid, err)
		return err
	}
	return nil
}

func (c *CpuSetSubsystem) Remove(cgroupPath string) error {
	subsystemCgroupPath, err := getCgroupPath(c.Name(), cgroupPath, false)
	if err != nil {
		logrus.Errorf("get %s path, err: %v", cgroupPath, err)
		return err
	}
	return os.RemoveAll(subsystemCgroupPath)
}
